﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Admin.Common;
using Zocono.WCS.Admin.Models.Comm;
using Zocono.WCS.Admin.Models.User;
using Zocono.WCS.Application.AppTraces;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoUser;

namespace Zocono.WCS.Admin.Controllers
{
    public abstract class BaseController : Controller
    {
        private readonly IMemoryCache _cache;
        private readonly TracesApp _tracesApp;
        private readonly IHttpContextAccessor _accessor;


        public BaseController(IMemoryCache memoryCache, TracesApp tracesApp, IHttpContextAccessor httpContextAccessor)
        {
            _cache = memoryCache;
            _tracesApp = tracesApp;
            _accessor = httpContextAccessor;
        }
        /// <summary>
        /// 保存操作日志
        /// </summary>
        public async Task AddTracesInfo()
        {
            var list = _cache.Get<List<FunctionInfoDto>>("function"); //获取缓存菜单信息
            if (list == null || list.Count == 0)
            {
                list = await _tracesApp.GetFunctionInfoAsync();
                if (list != null && list.Count > 0)
                    _cache.Set("function", list, new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(30)));
            }
            var url = GetAbsoluteUri().ToLower();
            var function = list.Find(e => e.URL.ToLower() == url);
            int type = 5;
            long id = 0;
            string fullName = "";
            if (function != null)
            {
                type = 5;
                id = function.ID;
                fullName = function.FullName;
            }
            await AddTracesInfo(type, id, fullName);

        }
        /// <summary>
        /// 保存操作日志
        /// </summary>
        /// <param name="type">类型 1=登录2=新增3=修改4=删除5=查看6=审核</param>
        /// <param name="functionid">菜单ID ，没有填 0</param>
        /// <param name="fullName">操作名称</param>
        /// <returns></returns>
        public async Task AddTracesInfo(int type, long functionid, string fullName)
        {
            var traces = new TracesInfo();
            var user = GetUserModel();
            if (user != null)
            {
                traces.UserID = user.UserID;
                traces.UserName = user.UserName;
            }
            else
            {
                traces.UserID = 0;
                traces.UserName = "";
            }
            traces.OperationType = type;
            traces.FunctionID = functionid;
            traces.FullName = fullName;
            traces.Parameter = "";
            if (_accessor.HttpContext.Request.ContentType != null)
            {
                var keys = _accessor.HttpContext.Request.Form.Keys;
                if (keys != null && keys.Count > 0)
                {
                    var dict = new Dictionary<string, string>();
                    foreach (string key in keys)
                    {
                        if (!key.Contains("Token"))
                            dict.Add(key, Request.Form[key]);
                    }
                    traces.Parameter = JsonUtils.Serialize(dict);
                }
            }
            traces.Ip = GetIP();
            traces.RequestUrl = GetAbsoluteUri();
            traces.LogTime = DateTime.Now;
            await _tracesApp.AddTracesAsync(traces);
        }

        private ISession _session => _accessor.HttpContext.Session;
        /// <summary>
        /// 设置本地cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>  
        /// <param name="minutes">过期时长，单位：分钟</param>      
        protected void SetCookies(string key, string value, int minutes = 30)
        {
            _accessor.HttpContext.Response.Cookies.Append(key, value, new CookieOptions
            {
                Expires = DateTime.Now.AddMinutes(minutes)
            });
        }
        /// <summary>
        /// 删除指定的cookie
        /// </summary>
        /// <param name="key">键</param>
        protected void DeleteCookies(string key)
        {
            _accessor.HttpContext.Response.Cookies.Delete(key);
        }

        /// <summary>
        /// 获取cookie的value
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>返回对应的值</returns>
        protected string GetCookiesValue(string key)
        {
            _accessor.HttpContext.Request.Cookies.TryGetValue(key, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }

        /// <summary>
        /// 添加Sesssion
        /// </summary>
        /// <param name="SesionStr"></param>
        /// <param name="Code"></param>
        public void SetSession(string SesionStr, string Code)
        {
            _session.SetString(SesionStr, Code);
        }

        /// <summary>
        /// 获取Session
        /// </summary>
        public string GetSession(string SesionStr)
        {
            string code = _session.GetString(SesionStr);
            return code;
        }
        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns></returns>
        public UserModel GetUserModel()
        {
            var token = GetCookiesValue("User_Token");
            if (!string.IsNullOrEmpty(token))
            {
                return JsonUtils.Deserialize<UserModel>(DesHelper.DecryptDES(token));
            }
            return null;
        }

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public string GetIP()
        {
            return _accessor.HttpContext.Connection.RemoteIpAddress.ToString();
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int Start
        {
            get
            {
                return _accessor.HttpContext.Request.Form["start"].ToInt32();
            }
        }
        /// <summary>
        /// 每页条数
        /// </summary>
        public int Length
        {
            get
            {
                return _accessor.HttpContext.Request.Form["length"].ToInt32();
            }
        }
        public int Draw
        {
            get { return _accessor.HttpContext.Request.Form["draw"].ToInt32(); }
        }

        /// <summary>
        /// 获取当前请求地址
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string GetAbsoluteUri()
        {
            return _accessor.HttpContext.Request.Path.ToString();
        }
        protected JsonResult CreateJsonGetResult(bool result)
        {
            if (result)
            {
                return Json(new ApiResult(true, "成功"));
            }
            else
            {
                return Json(new ApiResult { Result = false, Message = "失败" });
            }
        }
        protected JsonResult CreateJsonGetResult(bool result, string message)
        {
            return Json(new ApiResult(result, message));
        }
        public JsonResult CreateJsonGetResult<T>(bool Result, string message, T data)
        {
            return Json(new ApiResult<T> { Result = Result, Message = message, Data = data });
        }
    }
}
